package com.alias.DAO.interfaces.impl;

import com.alias.DAO.interfaces.CurrencyDAO;
import com.alias.HibernateUtil;
import com.alias.model.Currency;
import org.hibernate.Session;

import javax.swing.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class CurrencyDAOImpl implements CurrencyDAO {

    @Override
    public String getCurrencyById(int id) {
        Currency currency = null;
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            currency = (Currency) session.load(Currency.class, id);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);
        } finally {
            if (session != null && session.isOpen()){
                session.close();
            }
        }
        return currency.getCurrency();
    }

    @Override
    public Map<String, Integer> getCurrencyMap() {
        Map<String, Integer> currencyMap = new HashMap<String, Integer>();
        List<Currency> currencyList = new ArrayList<Currency>();
        Session session = null;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            currencyList = session.createCriteria(Currency.class).list();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Ошибка 'getAll'", JOptionPane.OK_OPTION);

        } finally {
            if (session != null && session.isOpen()){
                session.close();
            }
        }
        for (Currency c : currencyList){
            currencyMap.put(c.getCurrency(), c.getId());
        }
        return currencyMap;
    }
}
